<template>
  <div class="container">
    <h1>淘宝搜索建议</h1>
    
    <div class="search-box">
      <input 
        v-model="keyword" 
        type="text" 
        placeholder="输入关键词搜索..." 
        @input="onSearch"
        class="search-input"
      />
    </div>

    <div v-if="pending" class="loading">
      加载中...
    </div>

    <div v-else-if="error" class="error">
      错误: {{ error.message }}
    </div>

    <div v-else-if="suggestions && suggestions.length > 0" class="suggestions">
      <h2>搜索建议：</h2>
      <ul class="suggestion-list">
        <li 
          v-for="(item, index) in suggestions" 
          :key="index"
          class="suggestion-item"
        >
          <span class="keyword">{{ item[0] }}</span>
          <span class="score">热度: {{ formatScore(item[1]) }}</span>
        </li>
      </ul>
    </div>

    <div v-else class="no-data">
      暂无搜索建议
    </div>

    <div class="info">
      <p>当前关键词: <strong>{{ keyword }}</strong></p>
      <p>数据来源: 淘宝搜索建议接口</p>
      <p>预渲染状态: {{ isPrerendered ? '已预渲染' : '客户端渲染' }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

// 定义接口类型
interface TaobaoSuggestResponse {
  result: [string, string][]
  error?: string
}

// 初始关键词
const keyword = ref('卫衣')
let searchTimer: NodeJS.Timeout | null = null

// 使用 useFetch 进行数据获取，支持 SSR 和预渲染
const { data, pending, error, refresh } = await useFetch<TaobaoSuggestResponse>('/api/taobao-suggest', {
  query: {
    q: keyword
  },
  // 关键配置：确保在服务端和客户端都能工作
  server: true,
  lazy: false,
  // 初始数据，确保预渲染时有内容
  default: () => ({ result: [] })
})

// 计算属性：获取建议列表
const suggestions = computed(() => {
  return data.value?.result || []
})

// 检测是否为预渲染
const isPrerendered = ref(false)
if (process.server) {
  isPrerendered.value = true
}

// 搜索处理函数（防抖）
const onSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  searchTimer = setTimeout(() => {
    refresh()
  }, 500)
}

// 格式化热度分数
const formatScore = (score: string) => {
  const num = parseFloat(score)
  if (num > 100000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toFixed(0)
}
</script>

<style scoped>
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

h1 {
  color: #333;
  text-align: center;
  margin-bottom: 30px;
  font-size: 2rem;
}

h2 {
  color: #666;
  font-size: 1.3rem;
  margin-bottom: 15px;
}

.search-box {
  margin-bottom: 30px;
}

.search-input {
  width: 100%;
  padding: 15px 20px;
  font-size: 16px;
  border: 2px solid #ddd;
  border-radius: 8px;
  outline: none;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.search-input:focus {
  border-color: #ff6700;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 1.1rem;
}

.error {
  background: #fee;
  border: 1px solid #fcc;
  padding: 20px;
  border-radius: 8px;
  color: #c33;
  text-align: center;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 1.1rem;
}

.suggestions {
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.suggestion-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.suggestion-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 10px;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item:hover {
  background-color: #fafafa;
}

.keyword {
  font-size: 1rem;
  color: #333;
  font-weight: 500;
}

.score {
  font-size: 0.9rem;
  color: #999;
  padding: 4px 12px;
  background: #f5f5f5;
  border-radius: 12px;
}

.info {
  margin-top: 40px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  font-size: 0.95rem;
  color: #666;
}

.info p {
  margin: 8px 0;
}

.info strong {
  color: #ff6700;
}

@media (max-width: 600px) {
  .container {
    padding: 20px 15px;
  }
  
  h1 {
    font-size: 1.5rem;
  }
  
  .suggestion-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>